package br.com.listadecompras.activities;

/*import java.util.ArrayList;
import java.util.LinkedList;*/

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import br.com.listadecompras.DAO.GroupDAO;
import br.com.listadecompras.model.Group;
import br.com.listadecompras.model.Item;
import br.com.listadecompras.utils.Constantes;
import br.com.listadecompras.utils.DBHelper;
import br.com.listadecompras.utils.DialogHelper;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.SimpleExpandableListAdapter;
//import android.widget.SimpleExpandableListAdapter;

public class CriaGrupoActivity extends Activity {

	private static final String NAME = "TITLE";
    private static final String DESC = "DESC";
	
    private ExpandableListAdapter mAdapter;
	private ExpandableListView expListView;
	
	private List<Map<String, String>> groupData = new ArrayList<Map<String, String>>();
    private List<List<Map<String, String>>> childData = new ArrayList<List<Map<String, String>>>();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.cria_grupo);
	
		this.expListView = (ExpandableListView) findViewById(R.id.expListViewGroup);
		this.expListView.setTextFilterEnabled(true);		
		
		DBHelper db = new DBHelper(this, Constantes.DataBaseConstantes.DATABASE_NAME);
		Resources res = this.getResources();
		
		try {
			
			GroupDAO groupDAO = new GroupDAO(db.getReadableDatabase());
        	
        	ArrayList<Group> groups = groupDAO.getTodosGrupos();			
			
        	for (Group group : groups) {
        		Map<String, String> curGroupMap = new HashMap<String, String>();
	            this.groupData.add(curGroupMap);
	            curGroupMap.put(NAME, group.getNome());
	            curGroupMap.put(DESC, this.substringDescription(group.getDescricao()));
	            
	            List<Map<String, String>> children = new ArrayList<Map<String, String>>();
	            
	            for (Item item : group.getItens()) {
	            	Map<String, String> curChildMap = new HashMap<String, String>();
	                children.add(curChildMap);
	                curChildMap.put(NAME, item.getNome());
	                curChildMap.put(DESC, this.substringDescription(item.getDescricao()));
				}
	            this.childData.add(children);
			}
	
	        this.mAdapter = new SimpleExpandableListAdapter(
				                this,
				                this.groupData,
				                android.R.layout.simple_expandable_list_item_1,
				                new String[] { NAME, DESC },
				                new int[] { android.R.id.text1, android.R.id.text2 },
				                this.childData,
				                android.R.layout.simple_expandable_list_item_2,
				                new String[] { NAME, DESC },
				                new int[] { android.R.id.text1, android.R.id.text2 }
	        				);
	        
	        this.expListView.setAdapter(mAdapter);
        	
		} catch (Exception e) {
			new AlertDialog.Builder(this)
    		.setMessage(e.toString())
    		.setTitle(res.getString(R.string.dialogTitleError))
    		.setNeutralButton(res.getString(R.string.dialogOkOption), new DialogInterface.OnClickListener() {					
				public void onClick(DialogInterface arg0, int arg1) {}
			})
			.show();
			
		} finally {
			db.close();
			res = null;
		}
	}
	
	public void callAddGroupMethod(View view) {
		Intent intent = new Intent(this.getApplicationContext(), AdicionarGrupoActivity.class);
		startActivityForResult(intent, AdicionarGrupoActivity.CODIGO_ACTIVITY);
	}
	
	public void callCancelMethod(View view) {
		finish();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if (data != null) {
			Resources res = this.getResources();
			
			switch (requestCode) {
			case AdicionarGrupoActivity.CODIGO_ACTIVITY:
				if (insertGroupDataBase( adicionaGroupNaLista(data) ))
					DialogHelper.showDialog(this, 
							   res.getString(R.string.dialogTitleWarning), 
							   res.getString(R.string.dialogGrupoInseridoSucesso), 
							   res.getString(R.string.dialogOkOption));
				else
					DialogHelper.showDialog(this, 
							   res.getString(R.string.dialogTitleWarning),
							   res.getString(R.string.dialogProblemaInserirGrupo),
							   res.getString(R.string.dialogOkOption));
				break;
			default:
				break;
			}
		}
	}
	
	private Group adicionaGroupNaLista(Intent data) {
		Bundle extras = data.getExtras();
		
		String nomeNovoGrupo = extras.getString(Group.NOME);
		String descricaoGrupo = extras.getString(Group.DESCRICAO);
		
		Group group = new Group(nomeNovoGrupo, descricaoGrupo);
		
		//TODO: ver como adiciona item no adapter do expandableList
		
		return group;
	}
	
	private boolean insertGroupDataBase(Group group) {
		
		DBHelper dbHelper = new DBHelper(this, Constantes.DataBaseConstantes.DATABASE_NAME);
		
		try {
			GroupDAO groupDAO = new GroupDAO(dbHelper.getWritableDatabase());
			boolean result = groupDAO.insertGroup(group);
			
			return result;
			
		} catch (Exception e) {
			return false;
			
		} finally {
			dbHelper.close();
		}
	}
	
	private String substringDescription(String desc) {
		StringBuilder sub = new StringBuilder(desc);
		
		if (desc.length() >= 30)
			return sub.substring(0, 30).concat("...");
		else
			return desc;
	}
}
